from ib.ext.EWrapper import EWrapper
import config as cfg


handlermap = dict()
verbose = False
gcount = 0

def wrapperFactory(callbacklist):
    """ generate wrapper class with the configure
        set of callbacks i.e which messages will be
        handled or ignored"""
    wrapper = type('Wrapper', (object,EWrapper), callbacklist)
    return Wrapper

WrapperClass = wrapperFactory(cfg.callbacks)

w = WrapperClass()

#------------------------------------------------------------------
#            Micro Handlers
#------------------------------------------------------------------
def priceHdlr(price, field):
    global gcount
#    global cfg.outputfile

    if (gcount < 2):
        cfg.outputfile.write('call bid: %s\n' %(price))
        gcount+=1
    if (gcount == 2):
        cfg.outputfile.close()

handlermap['price_hdlr']= priceHdlr

#------------------------------------------------------------------
#            Handlers
#------------------------------------------------------------------
def controlHandler(tickerid, **kwargs):
    global handlermap
    if (kwargs['msgType'] == 'price'):
        handlermap['price_hdlr'](kwargs['msgPrice'],
                                 kwargs['msgField'])
        

class MetaHandler(EWrapper):
    def tickPrice(self, tickerId, field, price, canAutoExecute):
        controlHandler(tickerId, msgType = 'price', msgPrice = price,
                       msgField = field)
        
    def tickSize(self, tickerId, field, size):
        if( verbose):
            print 'sizeMsg\n'

    def tickString(self, tickerId, tickType, value):
        if( verbose): 
            print 'tickStringMsg'

    def tickSnapshotEnd(self, tickerId):
        """ not working for now"""
        print "FINITO"
        gfile.close()
    def tickOptionComputation(self, tickerId, field,
                              impliedVolatility, delta):
        print delta

    def nextValidId(self, orderId):
        print orderId

    def error(self, id=None, errorCode=None, errorMsg=None):
        print errorMsg

  
